
#include <windows.h>

#include "tlhelp32.h"

#include "lib.h"

#include "ProcessList.h"

#define DISPLAY_MODULES

/*
 * getProcessList()
 */
String
ProcessList::getProcessList() 
{ 
	String result;

#if 0	// this doesn't work on NT 4.0. 
		// we need to revisit this and use LoadLibrary / GetProcAddress
	HANDLE         hProcessSnap = NULL; 
    BOOL           bRet      = FALSE; 
    PROCESSENTRY32 pe32      = {0}; 
	String line;

    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); //  Take a snapshot of all processes in the system. 

    if (hProcessSnap == INVALID_HANDLE_VALUE) 
        return result; 
 
    pe32.dwSize = sizeof(PROCESSENTRY32);     //  Fill in the size of the structure before using it. 
 
    //  Walk the snapshot of the processes, and for each process, 
    //  display information. 
    if (::Process32First(hProcessSnap, &pe32)) 
    { 
        BOOL          bGotModule = FALSE; 
        MODULEENTRY32 me32       = {0}; 
		
		line.sprintf("%-25s%10s%10s%10s\r\n", "Process", "ID", "PPID", "THREADS");
		result += line;
		do 
        { 
			line.sprintf("%-25s%10d%10d%10d\r\n", pe32.szExeFile, pe32.th32ProcessID, pe32.th32ParentProcessID, pe32.cntThreads);
			result += line;

#ifdef	DISPLAY_MODULES
			HANDLE hModuleSnap = INVALID_HANDLE_VALUE; 
			MODULEENTRY32 me32; 
 
			if (pe32.th32ProcessID == 0)
				continue;
		
			//  Take a snapshot of all modules in the specified process.
			hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, pe32.th32ProcessID ); 
			if( hModuleSnap == INVALID_HANDLE_VALUE ) 
			{
				continue;
			}
			
			//  Set the size of the structure before using it. 
			me32.dwSize = sizeof( MODULEENTRY32 ); 
			
			//  Retrieve information about the first module, 
			//  and exit if unsuccessful 
			if( !::Module32First( hModuleSnap, &me32 ) ) 
			{ 
				CloseHandle( hModuleSnap );     // Must clean up the snapshot object! 
				continue;
			} 
			
			//  Now walk the module list of the process, 
			//  and display information about each module 
			do 
			{ 
				line.sprintf("\t%-25s%s\r\n", me32.szModule, me32.szExePath);
				result += line;
			} while( ::Module32Next( hModuleSnap, &me32 ) ); 
			
			//  Do not forget to clean up the snapshot object. 
			CloseHandle( hModuleSnap ); 
#endif
        } 
        while (::Process32Next(hProcessSnap, &pe32)); 
        bRet = TRUE; 
    } 
    else 
        bRet = FALSE;    // could not walk the list of processes 
 
    
    CloseHandle (hProcessSnap); // Do not forget to clean up the snapshot object. 

#endif
    
	return result; 
}

